﻿/*
 *  Source code courtesy of the desktopWeb.CodePlex.com community project. See MS-PL license on Codeplex.com. 
 *  This is beta code not intended for a production application.
 */

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Activities;
using System.Data;
using Microsoft.SharePoint.Client;
using System.ComponentModel;
using System.Drawing.Design;
using System.Net;

namespace MyData.Activities
{
  [Designer(typeof(MyData.Activities.AddItemDesigner))]
  public sealed class SharePointAddItem : SharePointBaseActivity
  {
    // Define an activity input arguments
    public InArgument<Dictionary<string, object>> FieldValues { get; set; }
    
    //CodeActivityContext
    protected override void Execute(NativeActivityContext context)
    {
      // Obtain the runtime value of the input arguments
      string url = context.GetValue(this.Url);
      string listTitle = context.GetValue(this.ListTitle);
      Dictionary<string, object> fieldValues = context.GetValue(this.FieldValues);

      if (this.NetworkCredential.Get(context) != null)
      {
        using (ClientContext clientContext = new ClientContext(url))
        {
          clientContext.Credentials = NetworkCredential.Get(context);

          Microsoft.SharePoint.Client.List list = clientContext.Web.Lists.GetByTitle(listTitle);
          ListItemCreationInformation itemCreateInfo = new ListItemCreationInformation();
          Microsoft.SharePoint.Client.ListItem listItem;

          listItem = list.AddItem(itemCreateInfo);

          foreach (KeyValuePair<string, object> v in fieldValues)
          {
            listItem[v.Key] = v.Value.ToString();
          }

          listItem.Update();
          //Batch Update
          try
          {
            clientContext.ExecuteQuery();
          }
          catch (Exception ex)
          {
            //Log exception in a production applicaiton
          }
        }
      }
      else
      {
        //NOTE: Throw specific exception in a production application
        throw new Exception("NetworkCredentials");
      }
    }
  }
}